<script lang="ts" setup>
import { loadScript } from '@paypal/paypal-js'

const emit = defineEmits(['close'])
const props = defineProps({
  showPay: {
    type: Boolean,
    default: false,
  },
  activityId: {
    type: [Number, String],
    default: null,
  },
})

// 挂载
onMounted(() => {
  initPaypal()
})

const orderID = ref('')
const showPaypalBtn = ref(true)
const showPaypalContainer = ref(false)
const { getUserInfo } = useUserStore()
const { setting } = storeToRefs(useUserStore())

// 充值
async function createPayOrder() {
  const { Data } = await useRequest.post('/Recharge', { activity_id: props.activityId })
  return Data
}

// 支付回调接口
async function payCallback(params: any) {
  const { Code } = await useRequest.post('/PayPalCallBack', params)
  if (Code === 0) {
    if (params?.status === 2) {
      showToast('Payment successful')
      getUserInfo() // 支付完成，刷新用户信息
    } else if (params?.status === 3) {
      showToast('Cancel Payment')
    } else {
      showToast('Payment failed')
    }
  }
  emit('close')
}

// 点击支付
async function initPaypal() {
  let paypal: any = {}
  if (!setting.value?.paypal) {
    return showToast('Paypal account available!')
  }

  try {
    paypal = await loadScript({
      clientId: setting.value.paypal,
      currency: 'USD',
    })
  } catch (err) {
    showToast('Failed: Loading paypal api')
  }

  if (paypal) {
    showPaypalBtn.value = false
    showPaypalContainer.value = true
    try {
      await paypal
        .Buttons({
          async createOrder() {
            const data = await createPayOrder()
            orderID.value = data?.id
            return data?.id
          },
          async onApprove() {
            const params = {
              token: orderID.value,
              status: 2,
            }
            await payCallback(params)
          },
          async onCancel() {
            const params = {
              token: orderID.value,
              status: 3,
            }
            await payCallback(params)
          },
          async onError(err: any) {
            const params = {
              token: orderID.value,
              status: 4,
              reason: JSON.stringify(err),
            }
            await payCallback(params)
          },
        })
        .render('#paypal-container')
    } catch (err) {
      showToast('paypal button error')
    }
  }
}
</script>

<template>
  <div class="pay-popup">
    <div
      id="paypal-container"
      class="paypal-container"></div>
  </div>
</template>

<style lang="scss" scoped>
.pay-popup {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 40px 24px;
  border-radius: 24px 24px 0px 0px;
  background: #21202f;
  .title {
    font-size: 16px;
    font-weight: 400;
    margin-bottom: 24px;
  }
  .pay-method {
    .method-item {
      width: 100%;
      height: 60px;
      padding: 0 20px;
      border-radius: 4px;
      border: 1px solid #fff;
      @include flexbox($ai: center);
      .pay-icon {
        font-size: 32px;
        margin-right: 20px;
      }
    }
  }
  .paypal-container {
    width: 100%;
  }
}
</style>
